/*
 * Copyright (c) 2021 KaiHong Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "ohos_types.h"
#include "iot_gpio.h"
#include "iot_pwm.h"
#include "iot_watchdog.h"
#include "hi_pwm.h"

#define IOT_TEST_PWM_GPIO9 9 // for pwm
#define IOT_PWM_PORT0 0

#define IOT_IO_NAME_GPIO_8 8    // button
#define PWM_DUTY 50      
#define M_INTERVAL_TIME_TICK 60
#define TICKS_DELAY  125*1000

static const uint16 g_tuneFreqs[] = {
    0,        // 40M Hz 对应的分频系数：
    1046 * 4, // 1046.50  1
    1174 * 4, // 1174.66  2
    1318 * 4, // 1318.51  3
    1396 * 4, // 1396.91  4
    1567 * 4, // 1567.99  5
    1760 * 4, // 1760.00  6
    1975 * 4, // 1975.53  7
    523 * 4,  // 523.25   1-  低一个8度的1
    587 * 4,  // 587.33   2-
    659 * 4,  // 659.26   3-   
    698 * 4,   // 698.46  4-
    783 * 4,  // 783.99   5-
    880 * 4,   // 880.00  6-
    987 * 4,  // 987.77   7-    
};

typedef enum
{
    D_DO = 1,  // 1
    D_RE,      // 2
    D_MI,      // 3
    D_FA,      // 4
    D_SO,      // 5
    D_LA,      // 6
    D_SI,      // 7
    C_DO,      // 1- 
    C_RE,      // 2- 
    C_MI,      // 3-
    C_FA,      // 4- 
    C_SO,      // 5- 
    C_LA,      // 6- 
    C_SI       // 7-     
} MusicTuneNotes;

typedef enum
{
    BEAT_1X4B = 1,   //4分之1拍为基础值1
    BEAT_1X2B,
    BEAT_3X4B,
    BEAT_1B,
    BEAT_3X2B = 6,
    BEAT_2B = 8,
    BEAT_3B = 12,
    BEAT_4B = 16
} MusicTuneInterval;

/*音符与时间间隔结构体*/
typedef struct
{
    MusicTuneNotes tuneNotes;       //音符
    MusicTuneInterval interval;     //时间间隔
} MusicNotesInterval;

/*曲谱*/
static const MusicNotesInterval g_interval[] = {
    {D_MI,BEAT_1X2B},{D_SO,BEAT_1X2B},{D_SO,BEAT_3X4B},{D_LA,BEAT_1X4B},{D_SO,BEAT_1X2B},{D_MI,BEAT_1X2B},{D_DO,BEAT_1X2B},
    {D_DO,BEAT_1X4B},{D_RE,BEAT_1X4B},{D_MI,BEAT_1X2B},{D_MI,BEAT_1X2B},{D_RE,BEAT_1X2B},{D_DO,BEAT_1X2B},{D_RE,BEAT_2B},
    {D_MI,BEAT_1X2B},{D_SO,BEAT_1X2B},{D_SO,BEAT_3X4B},{D_LA,BEAT_1X4B},{D_SO,BEAT_1X2B},{D_MI,BEAT_1X2B},{D_DO,BEAT_1X2B},
    {D_DO,BEAT_1X4B},{D_RE,BEAT_1X4B},{D_MI,BEAT_1X2B},{D_MI,BEAT_1X2B},{D_RE,BEAT_1X2B},{D_RE,BEAT_1X2B},{D_DO,BEAT_2B},
    {D_FA,BEAT_1B},{D_FA,BEAT_1B},{D_FA,BEAT_1X2B},{D_LA,BEAT_3X2B},{D_SO,BEAT_1B},{D_SO,BEAT_3X4B},{D_MI,BEAT_1X4B},
    {D_RE,BEAT_2B},{D_MI,BEAT_1X2B},{D_SO,BEAT_1X2B},{D_SO,BEAT_3X4B},{D_LA,BEAT_1X4B},{D_SO,BEAT_1X2B},{D_MI,BEAT_1X2B},
    {D_DO,BEAT_1X2B},{D_DO,BEAT_1X4B},{D_RE,BEAT_1X4B},{D_MI,BEAT_1X2B},{D_MI,BEAT_1X2B},{D_RE,BEAT_1X2B},{D_RE,BEAT_1X2B},
    {D_DO,BEAT_2B}
};

int music = 0;

/*按键响应函数*/
static void OnButtonPressed(char *arg)
{
    (void)arg;
    IoTGpioUnregisterIsrFunc(IOT_IO_NAME_GPIO_8);

    music = 1;
    printf("\r\n>>>>>>>>>>button is enter >>>.[%d]\r\n", music);

    IoTGpioRegisterIsrFunc(IOT_IO_NAME_GPIO_8, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, 
    OnButtonPressed, NULL);
}

/* 音乐处理*/
static void *BeeperMusicTask(const char *arg)
{
    (void)arg;
    
    printf("BeeperMusicTask start!\r\n");

    hi_pwm_set_clock(PWM_CLK_XTAL); // 设置时钟源为晶体时钟(40MHz，默认时钟源160MHz)

    while (1)
    {
        osDelay(M_INTERVAL_TIME_TICK);
        /*第一次点击按键播放，播放完以后按键才能继续生效*/
        if (music == 1)
        {
            for (size_t i = 0; i < sizeof(g_interval) / sizeof(g_interval[0]); i++)
            {  
                uint32 tune = g_interval[i].tuneNotes; // 音符
                uint16 freqDivisor = g_tuneFreqs[tune];
                uint32 tuneInterval = g_interval[i].interval * (TICKS_DELAY); // 音符时间
                IoTPwmStart(IOT_PWM_PORT0, PWM_DUTY, freqDivisor);
                usleep(tuneInterval);
                IoTPwmStop(IOT_PWM_PORT0);
                music = 0;
            }
        }
    }

    return NULL;
}

static void BeepMusicEntry(void)
{
    osThreadAttr_t attr;

    IoTGpioInit(IOT_IO_NAME_GPIO_8);   //button
    IoTGpioSetDir(IOT_IO_NAME_GPIO_8, IOT_GPIO_DIR_IN);

    IoTGpioRegisterIsrFunc(IOT_IO_NAME_GPIO_8, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, OnButtonPressed, NULL);

    IoTGpioInit(IOT_TEST_PWM_GPIO9);      //BWM
    IoTGpioSetDir(IOT_TEST_PWM_GPIO9, IOT_GPIO_DIR_OUT);
    IoTPwmInit(IOT_PWM_PORT0);

    IoTWatchDogDisable();

    attr.name = "BeeperMusicTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)BeeperMusicTask, NULL, &attr) == NULL)
    {
        printf("[LedExample] Falied to create LedTask!\n");
    }
}

//SYS_RUN(BeepMusicEntry);
APP_FEATURE_INIT(BeepMusicEntry);